import React, { useImperativeHandle, forwardRef, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native'
import { Provider as AntDesignProvider, Button, Modal, Toast, WhiteSpace, WingBlank, ActivityIndicator } from '@ant-design/react-native'
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import { connect } from 'react-redux'
import {
    getBalance,
    getGasLimit,
    getGasPrice,
    getNonce,
    sendTransaction,
    signTransaction,
    bigNumberFormatUnits,
} from 'react-native-web3-wallet';
import { pTx } from "../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../realm"
import NetworkList from "../utils/NetworkList"

const mapState = state => {
    return {
        wallet: state.wallet,
        network: state.network
    }
}

const Transaction = React.forwardRef((props, ref) => {
    const realm = useRealm();
    const wallet = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered('current = true');
    })[0];
    const rpcURL = NetworkList.find(item => item.chainId == wallet.chainId).rpcUrl
    const [open, setOpen] = useState(false)
    const [pageLoading, setPageLoading] = useState(true)
    const [loading, setLoading] = useState(false)
    const [payload, setPayload] = useState(null)
    const [params, setParams] = useState(null)
    const [method, setMethod] = useState(null)
    const [balance, setBalance] = useState(null)
    const [gasPrice, setGasPrice] = useState(null)
    const [nonce, setNonce] = useState(null)
    const [gasLimit, setGasLimit] = useState(null)


    useImperativeHandle(ref, () => ({
        // methods connected to `ref`
        setOpen,
        show
    }))
    // internal method
    const show = async (data) => {

        try {
            setOpen(true)
            setPayload(payload)
            setPageLoading(true)
            const { type, payload = {} } = JSON.parse(data) || {};
            const { method, params } = payload;
            setPayload(payload)
            setMethod(method)
            setParams(params)
            getBalance(
                rpcURL,
                wallet.address,
            )
                .then(res => {
                    setBalance(bigNumberFormatUnits(res, 18))
                })
                .catch(err => {
                    // console.log(err);
                });
            const nonce = await getNonce(
                rpcURL,
                params[0].from,
            )
            setNonce(nonce)
            const gasPrice = await getGasPrice(rpcURL)
            setGasPrice(gasPrice * 1)
            const gasLimit = await getGasLimit(rpcURL, params[0].from, params[0].to, bigNumberFormatUnits(params[0].value || "0"), params[0].data)
            setGasLimit(gasLimit * 1)
            // console.log(gasPrice.toString(), "gasPrice")
            // console.log(gasLimit.toString(), "gasLimit")
            // console.log(params[0], params[0].maxFeePerGas * 1, params[0].maxPriorityFeePerGas * 1, params[0].gas * 1)
            // console.log(gasLimit * 1, gasPrice * 1, params[0].value || "0")
            // console.log('gas', bigNumberFormatUnits(gasPrice.mul(gasLimit)));
            setPageLoading(false)
        } catch (error) {
            console.log(error, "error")
        }
    }
    const close = () => {
        setOpen(false)
        props.updateParentMessage({ id: method, error: "error", time: payload.time });
    }

    const clickSendTransaction = async () => {
        Modal.prompt(
            '请输入密码',
            '',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '确认',
                    onPress: (res) => {
                        return new Promise(async (resolve, reject) => {
                            // console.log(res, password)
                            resolve()
                            try {
                                setLoading(true)
                                const signedTx = await signTransaction(
                                    wallet.keystore,
                                    res,
                                    nonce,
                                    gasLimit,
                                    gasPrice,
                                    params[0].to,
                                    Number(wallet.chainId),
                                    bigNumberFormatUnits(params[0].value || "0"),
                                    params[0].data,
                                )
                                // console.log(signedTx)
                                const tx = await sendTransaction(rpcURL, signedTx)
                                // console.log(tx)
                                // console.log({ id: method, result: tx.hash, time: payload.time })
                                props.updateParentMessage({ id: method, result: tx.hash, time: payload.time });
                            } catch (error) {
                                console.log(error, "交易失败-------------------------")
                                props.updateParentMessage({ id: method, error: error, time: payload.time });
                            }
                            setLoading(false)
                            setOpen(false)
                        })
                    },
                },
            ],
            '',
            '',
        )
    }
    return (
        <Modal
            popup
            visible={open}
            style={styles.Modal}
            animationType="slide-up">
            <View style={styles.ModalBox}>
                <IconOutline name="close" style={styles.close} onPress={close} />
                {pageLoading ?
                    (<View >
                        <Text style={styles.title}>获取交易</Text>
                        <View style={styles.activityIndicator} >
                            <ActivityIndicator size="xl" />
                        </View>
                    </View>) : (
                        <View>
                            <Text style={styles.title}>交易详情</Text>
                            <View style={styles.page} >
                                <View style={styles.row} >
                                    <Text style={styles.label}>余额</Text>
                                    <Text style={styles.value}>{balance} BNB</Text>
                                </View>
                                <View style={styles.row} >
                                    <Text style={styles.label}>发起地址</Text>
                                    <Text style={styles.value}>{params[0].from}</Text>
                                </View>
                                <View style={styles.row} >
                                    <Text style={styles.label}>收款地址</Text>
                                    <Text style={styles.value}>{params[0].to}</Text>
                                </View>
                                <View style={styles.row} >
                                    <Text style={styles.label}>网络费</Text>
                                    <View style={styles.rowBox} >
                                        <Text style={styles.value}>{bigNumberFormatUnits((params[0].gas * 1 || 31500) * (params[0].maxFeePerGas / gasPrice || gasLimit / 10000), 9)} BNB    </Text>
                                        <Text style={styles.valueMin}>≈ Gas({params[0].gas * 1 || 31500}) * Gas Price({params[0].maxFeePerGas / gasPrice || gasLimit / 10000} Gwei)</Text>
                                    </View>
                                </View>
                                <Button type="primary" loading={loading} disabled={loading} onPress={clickSendTransaction}>
                                    确定
                                </Button>
                            </View>
                        </View>
                    )
                }
            </View>
        </Modal>
    );
})

export default connect(mapState, {}, null, { forwardRef: true })(Transaction)

const styles = StyleSheet.create({
    Modal: {
        borderTopRightRadius: pTx(15),
        borderTopLeftRadius: pTx(15),
    },
    ModalBox: {
        position: "relative",
    },
    title: {
        textAlign: "center",
        paddingVertical: pTx(15),
        borderWidth: pTx(1),
        borderColor: "rgba(0,0,0,0.08)",
    },
    close: {
        position: "absolute",
        right: pTx(15),
        top: pTx(20),
        fontSize: pTx(16),
        zIndex: 9
    },
    activityIndicator: {
        minHeight: pTx(150),
        justifyContent: "center"
    },
    page: {
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(25),
    },
    row: {
        flexDirection: "row",
        marginBottom: pTx(15),
        paddingBottom: pTx(15),
        borderBottomWidth: pTx(1),
        borderColor: "rgba(0,0,0,0.08)",
    },
    label: {
        minWidth: pTx(100),
        fontSize: pTx(13),
        color: "#999"
    },
    value: {
        maxWidth: pTx(240),
        fontSize: pTx(13),
        color: "#333",
        flexWrap: "wrap",
    },
    valueMin: {
        fontSize: pTx(10),
        color: "#333",
        opacity: 0.4
    }
})